/**
 // 使用示例
 const viewer = new Cesium.Viewer('cesiumContainer');
 const cesiumUtils = new DrawTools(viewer);

 // 绘制点
 cesiumUtils.draw("point", {}, handler);

 // 绘制多段线
 cesiumUtils.draw("polyline", {}, handler);

 // 绘制多边形
 cesiumUtils.draw("polygon", {}, handler);**/
let mouse = null;

class DrawTools {
  constructor(viewer) {
    this.viewer = viewer;
    this.tempEntities = [];
    this.handler = null;
    this.labelEntity = null;
    this.labelPos = null;
    this.viewer.scene.globe.depthTestAgainstTerrain = false;
  }

  drawPolyline(positions, options = {}, dynamic = false) {
    let dynamicPositions = new Cesium.CallbackProperty(() => {
      return positions;
    }, false);

    return this.viewer.entities.add(
      new Cesium.Entity({
        id: options.id,
        polyline: {
          positions: dynamic ? dynamicPositions : positions,
          width: 2,
          arcType: Cesium.ArcType.RHUMB,
          clampToGround: true,
          material: Cesium.Color.RED,
        },
      })
    );
  }

  drawPolygon(positions, options = {}) {
    return this.viewer.entities.add(
      new Cesium.Entity({
        id: options.id,
        polygon: {
          hierarchy: new Cesium.PolygonHierarchy(positions),
          clampToGround: true,
          material: Cesium.Color.YELLOW.withAlpha(0.2),
          classificationType: Cesium.ClassificationType.BOTH, // 贴地表和贴模型,如果设置了，这不能使用挤出高度
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          arcType: Cesium.ArcType.RHUMB,
        },
      })
    );
  }

  drawPoint(position, options = {}) {
    return this.viewer.entities.add(
      new Cesium.Entity({
        id: options.id,
        position,
        point: {
          color: Cesium.Color.BLUE,
          pixelSize: 10,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 相对于对象的原点的水平位置
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
        },
      })
    );
  }

  addLabel(centerPoint, text, options = {}) {
    return this.viewer.entities.add(
      new Cesium.Entity({
        position: new Cesium.CallbackProperty(() => {
          return centerPoint;
        }, false),
        id: options.id,
        label: {
          text: text,
          font: "14px sans-serif",
          style: Cesium.LabelStyle.FILL_AND_OUTLINE, // FILL  FILL_AND_OUTLINE OUTLINE
          fillColor: Cesium.Color.YELLOW,
          showBackground: true, // 指定标签后面背景的可见性
          backgroundColor: new Cesium.Color(0.165, 0.165, 0.165, 0.8), // 背景颜色
          backgroundPadding: new Cesium.Cartesian2(6, 6), // 指定以像素为单位的水平和垂直背景填充padding
          pixelOffset: new Cesium.Cartesian2(0, -45),
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
        },
      })
    );
  }

  removeEntity(entity) {
    if (entity) {
      this.viewer.entities.remove(entity);
    }
  }

  removeById(id) {
    const entity = this.viewer.entities.getById(id);
    if (entity) {
      this.viewer.entities.remove(entity);
    }
  }

  removeHandler() {
    if (this.handler) {
      document.getElementsByClassName("cesium-viewer")[0].style.cursor = mouse;
      this.viewer.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_CLICK
      );
      this.viewer.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.MOUSE_MOVE
      );
      this.viewer.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.RIGHT_CLICK
      );
      this.handler && this.handler.destroy(); //关闭事件句柄
      this.handler = null;
    }
  }

  getCenterOfGravityPoint(mPoints) {
    let centerPoint = mPoints[0];
    for (let i = 1; i < mPoints.length; i++) {
      centerPoint = Cesium.Cartesian3.midpoint(
        centerPoint,
        mPoints[i],
        new Cesium.Cartesian3()
      );
    }
    return centerPoint;
  }

  draw(type, handler,callback) {
    let that = this;
    let tempPoints = [];
    // 开启深度检测
    this.viewer.scene.globe.depthTestAgainstTerrain = false;
    handler && this.removeHandler();
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);

    switch (type) {
      case "point":
        this.handler.setInputAction(function (movement) {
          document.getElementsByClassName("cesium-viewer")[0].style.cursor =
            "crosshair";
          let position = that.viewer.camera.pickEllipsoid(
            movement.endPosition,
            that.viewer.scene.globe.ellipsoid
          );
          that.labelEntity && that.removeEntity(that.labelEntity);
          that.labelEntity = that.addLabel(position, "左键单击绘制点");
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        this.handler.setInputAction(function (clickEvent) {
          document.getElementsByClassName("cesium-viewer")[0].style.cursor =
            "crosshair";
          let position = that.viewer.camera.pickEllipsoid(
            clickEvent.position,
            that.viewer.scene.globe.ellipsoid
          );
          if (position === undefined) {
            console.log("没有获取到坐标");
          } else {
            let point = that.drawPoint(position);
            that.labelPos = position;
            that.tempEntities.push(point);
            that.labelEntity && that.removeEntity(that.labelEntity);
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        // 右击单击停止绘制
        this.handler.setInputAction(function () {
          that.labelEntity && that.removeEntity(that.labelEntity);
          that.removeHandler();
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        break;
      case "polyline":
        // 鼠标移动事件
        this.handler.setInputAction(function (movement) {
          document.getElementsByClassName("cesium-viewer")[0].style.cursor =
            "crosshair";
          let position = that.viewer.camera.pickEllipsoid(
            movement.endPosition,
            that.viewer.scene.globe.ellipsoid
          );
          that.labelEntity && that.removeEntity(that.labelEntity);
          that.labelEntity = that.addLabel(
            position,
            "单击绘制第" +
              Number(tempPoints.length + 1) +
              "个点，右键单击完成绘制"
          );
          if (tempPoints.length > 0) {
            that.removeById("tempLine");
            that.drawPolyline(
              [tempPoints[tempPoints.length - 1], position],
              { id: "tempLine" },
              true
            );
          }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        // 左键点击操作
        this.handler.setInputAction(function (click) {
          document.getElementsByClassName("cesium-viewer")[0].style.cursor =
            "crosshair";
          let position = that.viewer.camera.pickEllipsoid(
            click.position,
            that.viewer.scene.globe.ellipsoid
          );
          tempPoints.push(position);
          let tempLength = tempPoints.length;
          let point = that.drawPoint(tempPoints[tempLength - 1], {
            id: that.tempEntities.length,
          });
          that.tempEntities.push(point);
          if (tempLength > 1) {
            let pointline = that.drawPolyline(
              [tempPoints[tempLength - 2], tempPoints[tempLength - 1]],
              { id: "pointline" + that.tempEntities.length },
              false
            );
            that.tempEntities.push(pointline);
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        // 右键点击操作
        this.handler.setInputAction(function (click) {
          let tempLength = tempPoints.length;
          if (tempLength < 2) {
            alert("请选择2个以上的点再执行绘制");
          } else {
            that.removeHandler();
            that.removeById("tempLine");
            that.labelPos = that.getCenterOfGravityPoint(tempPoints);
            that.labelEntity && that.removeEntity(that.labelEntity);
            setTimeout(() => (that.addPopShow = true), 100);
          }
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        break;
      case "polygon":
        // 鼠标移动事件
        this.handler.setInputAction(function (movement) {
          document.getElementsByClassName("cesium-viewer")[0].style.cursor =
            "crosshair";
          let position = that.viewer.camera.pickEllipsoid(
            movement.endPosition,
            that.viewer.scene.globe.ellipsoid
          );
          that.labelEntity && that.removeEntity(that.labelEntity);
          that.labelEntity = that.addLabel(
            position,
            "单击绘制第" +
              Number(tempPoints.length + 1) +
              "个点，右键单击完成绘制"
          );
          if (tempPoints.length > 0) {
            that.removeById("tempLine");
            that.drawPolyline(
              [tempPoints[tempPoints.length - 1], position],
              { id: "tempLine" },
              true
            );
          }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        // 左键点击操作
        this.handler.setInputAction(function (click) {
          document.getElementsByClassName("cesium-viewer")[0].style.cursor =
            "crosshair";
          let position = that.viewer.camera.pickEllipsoid(
            click.position,
            that.viewer.scene.globe.ellipsoid
          );
          tempPoints.push(position);
          let tempLength = tempPoints.length;
          let point = that.drawPoint(tempPoints[tempLength - 1], {
            id: "point" + that.tempEntities.length,
          });
          that.tempEntities.push(point);
          if (tempLength > 1) {
            let pointline = that.drawPolyline(
              [tempPoints[tempLength - 2], tempPoints[tempLength - 1]],
              { id: "pointline" + that.tempEntities.length },
              false
            );
            that.tempEntities.push(pointline);
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        // 右键点击操作
        this.handler.setInputAction(function (click) {
          let tempLength = tempPoints.length;
          if (tempLength < 2) {
            alert("请选择2个以上的点再执行绘制");
          } else {
            that.removeHandler();
            that.removeById("tempLine");
            let pointline = that.drawPolyline(
              [tempPoints[0], tempPoints[tempLength - 1]],
              { id: "pointline" + that.tempEntities.length },
              false
            );
            that.tempEntities.push(pointline);
            let polygon = that.drawPolygon(tempPoints, {
              id: "pointline" + that.tempEntities.length,
            })
            callback(polygon)
            that.tempEntities.push(
              polygon
            );

            that.labelPos = that.getCenterOfGravityPoint(tempPoints);
            that.labelEntity && that.removeEntity(that.labelEntity);
            setTimeout(() => (that.addPopShow = true), 100);

          }
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        break;
    }
  }

  removeAllEntity(){
    this.tempEntities.forEach(entity=>{
      this.removeEntity(entity)
    })
    this.tempEntities=[]
  }
}

export default DrawTools;
